import React, {
  AnchorHTMLAttributes,
  ButtonHTMLAttributes,
  FC,
  PropsWithChildren,
  ReactNode,
  useMemo
} from 'react';
import { Loading, StyledButton, Text } from './style';

export enum BUTTON_TYPE {
  primary = 'primary',
  primaryOutline = 'primaryOutline',
  secondary = 'secondary',
  secondaryOutline = 'secondaryOutline',
  tertiary = 'tertiary',
  outline = 'outline',
  inversePrimary = 'inversePrimary',
  inverseSecondary = 'inverseSecondary',
  inverseOutline = 'inverseOutline'
}

export const buttonTypes = {
  primary: 'primary',
  primaryOutline: 'primaryOutline',
  secondary: 'secondary',
  secondaryOutline: 'secondaryOutline',
  tertiary: 'tertiary',
  outline: 'outline',
  inversePrimary: 'inversePrimary',
  inverseSecondary: 'inverseSecondary',
  inverseOutline: 'inverseOutline'
};

export type IButtonType = keyof typeof buttonTypes;

export enum BUTTON_SIZE {
  large = 'large',
  default = 'default',
  small = 'small'
}

export interface ICustomButtonProps {
  /** 是否禁用 */
  disabled?: boolean;
  /** 是否加载中 */
  isLoading?: boolean;
  /** 是否是a标签 */
  isLink?: boolean;
  /** 是否替换加载中文本 */
  loadingText?: ReactNode;
  /** 按钮大小 */
  size?: BUTTON_SIZE;
  /** 按钮类型 */
  buttonType?: BUTTON_TYPE;
  /** 无效点击 */
  isUnclickable?: boolean;
}

export type IButtonProps = ICustomButtonProps &
  AnchorHTMLAttributes<HTMLAnchorElement> &
  ButtonHTMLAttributes<HTMLButtonElement>;

export const Button: FC<PropsWithChildren<IButtonProps>> = (props) => {
  const { children, isLink, isLoading, loadingText } = props;
  const btnType = useMemo(() => {
    if (isLink) {
      return 'a';
    }
  }, [isLink]);

  return (
    <StyledButton as={btnType} {...props} data-testid="button">
      <Text>{children}</Text>
      {isLoading && <Loading>{loadingText || 'loading...'}</Loading>}
    </StyledButton>
  );
};

Button.defaultProps = {
  isLoading: false,
  loadingText: null,
  isLink: false,
  buttonType: BUTTON_TYPE.tertiary,
  disabled: false,
  isUnclickable: false,
  size: BUTTON_SIZE.default
};

export default Button;
